package com.luhuiguo.cms.server.web.multipart;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 * @author LuHuiguo
 * @version $Id: StreamingMultipartFile.java 145 2010-05-06 05:23:59Z luhuiguo@gmail.com $
 */
public class StreamingMultipartFile implements MultipartFile {

    private FileItemStream item;
    private long size = -1;
    byte[] bytes;

    public StreamingMultipartFile(FileItemStream item) throws IOException {

        this.item = item;
        getBytes();

    }

    public String getName() {
        return this.item.getFieldName();
    }

    public String getOriginalFilename() {
        String filename = this.item.getName();
        if (filename == null) {
            // Should never happen.
            return "";
        }
        // check for Unix-style path
        int pos = filename.lastIndexOf("/");
        if (pos == -1) {
            // check for Windows-style path
            pos = filename.lastIndexOf("\\");
        }
        if (pos != -1)  {
            // any sort of path separator found
            return filename.substring(pos + 1);
        }
        else {
            // plain name
            return filename;
        }
    }

    public String getContentType() {
        return item.getContentType();
    }

    public boolean isEmpty() {
        return false; // TODO
    }

    public long getSize() {
        if (size > 0) {
            try {
                return getBytes().length;
            } catch (IOException e) {

                throw new MultipartException("Something went wrong here");
            }

        }
        return size;
    }

    public byte[] getBytes() throws IOException {
        if (bytes == null) {
            bytes = IOUtils.toByteArray(item.openStream());
        }

        return bytes;

    }

    public InputStream getInputStream() throws IOException {
        throw new UnsupportedOperationException("not possible");

    }

    public void transferTo(File dest) throws IOException, IllegalStateException {
        throw new UnsupportedOperationException("not possible");
    }
}